package com.yxh.lib_base.util.photo.picture_selector

import android.app.Activity
import android.content.Context
import android.util.Log
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.GsonUtils
import com.yxh.lib_base.util.LogUtils
import com.luck.picture.lib.R
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.style.*
import com.yxh.lib_base.ext.dp2px
import com.yxh.lib_base.ext.getColors
import com.yxh.lib_base.ext.getStrings
import com.yxh.lib_base.ext.lazyNone
import com.yxh.lib_base.util.photo.IPhotoSelectorEngine
import com.yxh.lib_base.util.photo.MimeType
import com.yxh.lib_base.util.photo.MimeTypeMenu

/**
 * 作者 : yuan_xh
 * 时间 : 2022/7/6 16:23
 * 说明 : 图片选择器 - 基于PictureSelector封装
 */
class PictureSelectorImpl : IPhotoSelectorEngine {
    private val TAG = "PictureSelectorUtils"

    private val _ImageLoadEngine by lazyNone { SelectorGlideEngine.createGlideEngine() }

    private fun getPictureSelector(current: Any) = kotlin.run {
        when (current) {
            is Fragment -> PictureSelector.create(current)
            is Activity -> PictureSelector.create(current)
            is Context -> PictureSelector.create(current)
            else -> {
                throw ClassCastException("不支持的类型")
            }
        }
    }

    override fun openPhotoSingle(
        any: Any,
        mimeMenu: MimeTypeMenu.() -> Int,
        onResult: (Int, String) -> Unit
    ) {
        openPhotoSingle(any, mimeMenu.invoke(MimeTypeMenu()), onResult)
    }

    override fun openPhotoSingle(
        any: Any, type: Int, onResult: (Int, String) -> Unit
    ) {
        val _type = when (type) {
            MimeType.TYPE_IMAGE -> SelectMimeType.ofImage()
            MimeType.TYPE_VIDEO -> SelectMimeType.ofVideo()
            else -> SelectMimeType.ofAll()
        }
        openPhoto(any, _type, {
            setMaxSelectNum(1)
        }) { photos ->
            if (photos != null && photos.isNotEmpty()) {
                val photo: LocalMedia = photos[0]
                Log.d(TAG, "返回数据：${GsonUtils.toJson(photo)}")
//                Log.d(TAG, "openPhotoSingle: ")
                //视频 去编辑
                when (val mediaType = PictureMimeType.getMimeType(photo.mimeType)) {
                    SelectMimeType.TYPE_VIDEO -> {
                        //视频
                        val videoPath = photo.realPath
                        onResult.invoke(MimeType.TYPE_VIDEO, videoPath)
                    }
                    SelectMimeType.TYPE_IMAGE -> {
                        //图片
                        val originalPath = photo.realPath
                        onResult.invoke(MimeType.TYPE_IMAGE, originalPath)
                    }
                    else -> {
                        //直接不支持返回其他类型
                        LogUtils.e(TAG, "不支持的 mimeType : $mediaType")
                    }
                }
            }
        }
    }

    override fun openPhotoMultiple(
        any: Any,
        type: Int,
        max: Int,
        onResult: (List<Pair<Int, String>>) -> Unit
    ) {
        val _type = when (type) {
            MimeType.TYPE_IMAGE -> SelectMimeType.ofImage()
            MimeType.TYPE_VIDEO -> SelectMimeType.ofVideo()
            else -> SelectMimeType.ofAll()
        }
        openPhoto(any, _type, {
            setMaxSelectNum(max)
        }) { photos ->
            photos.map { photo ->
                LogUtils.d(TAG, "返回数据：$photo")
                //视频 去编辑
                when (val mediaType = PictureMimeType.getMimeType(photo.mimeType)) {
                    SelectMimeType.TYPE_VIDEO -> {
                        //视频
                        Pair(MimeType.TYPE_VIDEO, photo.realPath)
                    }
                    SelectMimeType.TYPE_IMAGE -> {
                        //图片
                        Pair(MimeType.TYPE_IMAGE, photo.realPath)
                    }
                    else -> {
                        //直接不支持返回其他类型
                        LogUtils.e(TAG, "不支持的 mimeType : $mediaType")
                        Pair(MimeType.TYPE_ALL, photo.realPath)
                    }
                }
            }.filterNot { it.first == MimeType.TYPE_ALL }.apply(onResult)

        }
    }

    override fun openCamera(current: Any, onResult: (Int, String) -> Unit) {
        // 单独拍照
        getPictureSelector(current)
            .openCamera(SelectMimeType.ofImage()) // 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
            .forResultActivity(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: java.util.ArrayList<LocalMedia>) {
                    val photo: LocalMedia = result[0]
                    LogUtils.d(TAG, "返回数据：$photo")
                    //视频 去编辑
                    when (val mediaType = PictureMimeType.getMimeType(photo.mimeType)) {
                        SelectMimeType.TYPE_VIDEO -> {
                            //视频
                            val videoPath = photo.realPath
                            onResult.invoke(MimeType.TYPE_VIDEO, videoPath)
                        }
                        SelectMimeType.TYPE_IMAGE -> {
                            //图片
                            val originalPath = photo.realPath
                            onResult.invoke(MimeType.TYPE_IMAGE, originalPath)
                        }
                        else -> {
                            //直接不支持返回其他类型
                            LogUtils.e(TAG, "不支持的 mimeType : $mediaType")
                        }
                    }
                }

                override fun onCancel() = Unit
            })

    }


    /**
     * 打开相册
     * @param builder 配置
     * @param onResult 返回值
     * */
    private fun openPhoto(
        current: Any, chooseMode: Int,
        builder: PictureSelectionModel.() -> Unit,
        onResult: (ArrayList<LocalMedia>) -> Unit
    ) {
        var modul = getPictureSelector(current).openGallery(chooseMode)
            .setSelectorUIStyle(mSelectorStyle)
            .setImageEngine(_ImageLoadEngine)
        builder.invoke(modul)
        modul.forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(photos: ArrayList<LocalMedia>) {
                onResult.invoke(photos)
            }
            override fun onCancel() {
                LogUtils.e(TAG, "取消选择")
            }
        })
    }

    //主题样式 -仿微信主题
    private val mSelectorStyle by lazy(LazyThreadSafetyMode.NONE) {
        PictureSelectorStyle().apply {
            windowAnimationStyle = PictureWindowAnimationStyle().apply {
                setActivityEnterAnimation(R.anim.ps_anim_up_in)
                setActivityExitAnimation(R.anim.ps_anim_down_out)
//                setActivityEnterAnimation(R.anim.tcore_translate_in_b2t_anim)
//                setActivityExitAnimation(R.anim.tcore_translate_out_t2b_anim)
            }
            selectMainStyle = weChatMainStyle
            titleBarStyle = weChatTitleBarStyle
            bottomBarStyle = weChatBottomBarStyle
        }
    }

    //仿微信主题- 头部TitleBar 风格
    private val weChatTitleBarStyle by lazy(LazyThreadSafetyMode.NONE) {
        TitleBarStyle().apply {
            isHideCancelButton = true
            isAlbumTitleRelativeLeft = true
            titleAlbumBackgroundResource = R.drawable.ps_album_bg
            titleDrawableRightResource = R.drawable.ps_ic_grey_arrow
            previewTitleLeftBackResource = R.drawable.ps_ic_normal_back
        }
    }

    //仿微信主题-  主体风格
    private val weChatMainStyle by lazy(LazyThreadSafetyMode.NONE) {
        SelectMainStyle().apply {
            isSelectNumberStyle = true
            isPreviewSelectNumberStyle = false
            isPreviewDisplaySelectGallery = true
            selectBackground = R.drawable.ps_default_num_selector
            previewSelectBackground = R.drawable.ps_preview_checkbox_selector
            selectNormalBackgroundResources =
                R.drawable.ps_select_complete_normal_bg
            selectNormalTextColor = getColors(R.color.ps_color_53575e)
            selectNormalText = getStrings(R.string.ps_send)
            adapterPreviewGalleryBackgroundResource =
                R.drawable.ps_preview_gallery_bg
            adapterPreviewGalleryItemSize = 52f.dp2px()
            previewSelectText = getStrings(R.string.ps_select)
            previewSelectTextSize = 14
            previewSelectTextColor = getColors(R.color.ps_color_white)
            previewSelectMarginRight = 6f.dp2px()
            selectBackgroundResources = R.drawable.ps_select_complete_bg
            selectText = getStrings(R.string.ps_send_num)
            selectTextColor = getColors(R.color.ps_color_white)
            mainListBackgroundColor = getColors(R.color.ps_color_black)
            isCompleteSelectRelativeTop = true
            isPreviewSelectRelativeBottom = true
            isAdapterItemIncludeEdge = false
        }
    }

    //仿微信主题-  底部NavBar 风格
    private val weChatBottomBarStyle by lazy(LazyThreadSafetyMode.NONE) {
        // 底部NavBar 风格
        BottomNavBarStyle().apply {
            bottomPreviewNarBarBackgroundColor =
                getColors(R.color.ps_color_half_grey)
            bottomPreviewNormalText = getStrings(R.string.ps_preview)
            bottomPreviewNormalTextColor = getColors(R.color.ps_color_9b)
            bottomPreviewNormalTextSize = 16
            isCompleteCountTips = false
            bottomPreviewSelectText = getStrings(R.string.ps_preview_num)
            bottomPreviewSelectTextColor = getColors(R.color.ps_color_white)
        }
    }


}